package com.zhang.learn.thymeleaf.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

public class MyLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        // 根据请求头判断语言
        Locale locale = null;
        String language = request.getHeader("lang");
        if (StringUtils.isNotBlank(language)) {
            return Locale.forLanguageTag(language);
        }

        String lanStr = request.getParameter("lang");
        if (lanStr != null && lanStr.contains("_")) {
            String[] localeInfos = lanStr.split("_");
            locale = new Locale(localeInfos[0], localeInfos[1]);
            return locale;
        } else if (lanStr != null && lanStr.contains("-")) {
            String[] localeInfos = lanStr.split("_");
            locale = new Locale(localeInfos[0], localeInfos[1]);
            return locale;
        }

        return Locale.getDefault();
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
}
